// src/api/course.js
import request from '@/utils/request';

// 通用的认证头部
const getAuthHeader = () => {
  return { 'Authorization': `Bearer ${localStorage ? localStorage.getItem('token') || '' : ''}` };
}

// 获取课程列表（分页）
export function getCourse(pageNum, pageSize, name) {
    return request({
        url: '/course/list',
        method: 'GET',
        headers: getAuthHeader(),
        params: {
            pageNum,
            pageSize,
            name
        }
    })
}

// 获取页面总数
export function getPage(pageSize) {
    return request({
        url: '/course/page-count',
        method: 'GET',
        headers: getAuthHeader(),
        params: { pageSize }
    })
}

// 获取课程详情
export function getCourseDetail(id) {
    return request({
        url: '/course/info/detailByCourseId',
        method: 'GET',
        headers: getAuthHeader(),
        params: { courseId: id }
    })
}

// 添加课程
export function addCourse(courseData) {
    // 创建FormData对象，后端期望接收表单数据
    const formData = new FormData();
    formData.append('courseName', courseData.courseName);
    formData.append('courseDesc', courseData.courseDesc);
    // 如果有文件对象，添加文件
    if (courseData.file) {
        formData.append('file', courseData.file);
    }
    
    // 创建请求头，同时包含认证信息和内容类型
    const headers = getAuthHeader();
    headers['Content-Type'] = 'multipart/form-data';
    
    return request({
        url: '/course/add',
        method: 'POST',
        headers: headers,
        data: formData
    })
}

// 删除课程
export function deleteCourse(id) {
    return request({
        url: '/course/delete',
        method: 'POST',
        headers: getAuthHeader(),
        params: { courseId: id }
    })
}

// ============ 章节管理 API ============

// 获取课程章节列表
export function getChapterList(courseId) {
    return request({
        url: '/course/chapter/list',
        method: 'GET',
        params: { courseId }
    })
}

// 添加章节
export function addChapter(data) {
    return request({
        url: '/course/chapter/add',
        method: 'POST',
        data
    })
}

// 更新章节
export function updateChapter(data) {
    return request({
        url: '/course/chapter/update',
        method: 'PUT',
        data
    })
}

// 删除章节
export function deleteChapter(id) {
    return request({
        url: `/course/chapter/delete/${id}`,
        method: 'DELETE'
    })
}

// ============ 视频管理 API ============

// 获取章节视频列表
export function getVideoList(chapterId) {
    return request({
        url: '/course/video/list',
        method: 'GET',
        params: { chapterId }
    })
}

// 添加视频
export function addVideo(data) {
    return request({
        url: '/course/video/add',
        method: 'POST',
        data
    })
}

// 更新视频
export function updateVideo(data) {
    return request({
        url: '/course/video/update',
        method: 'PUT',
        data
    })
}

// 删除视频
export function deleteVideo(id) {
    return request({
        url: `/course/video/delete/${id}`,
        method: 'DELETE'
    })
}